package com.example.translateappjava.Fragment;

import android.content.SharedPreferences;
import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.widget.Toolbar;

import com.example.translateappjava.Activity.HomeFragmentActivity.RobotActivity;
import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.R;
import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Utils.Message;
import com.example.translateappjava.Utils.MessageAdapter;
import com.google.android.material.progressindicator.LinearProgressIndicator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShuaFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShuaFragment extends Fragment implements ChatGptHelper.OnChatGptResponseListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private final Handler handler = new Handler(Looper.getMainLooper());



    public LinearProgressIndicator linearProgressIndicator;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public static List<Message> messageList;
    public static MessageAdapter messageAdapter;

    public ShuaFragment() {
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShuaFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShuaFragment newInstance(String param1, String param2) {
        ShuaFragment fragment = new ShuaFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.fragment_shua, container, false);
            RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
            EditText editTextMessage = view.findViewById(R.id.editTextMessage);
            Button buttonSend = view.findViewById(R.id.buttonSend);
             Toolbar toolbar = view.findViewById(R.id.toolbar);

            linearProgressIndicator = view.findViewById(R.id.linear_2);
            messageList = new ArrayList<>();
            messageAdapter = new MessageAdapter(messageList);
            ThemeUtilsActivity.applyTheme(view);

            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setAdapter(messageAdapter);

            buttonSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String messageText = editTextMessage.getText().toString().trim();
                    if (!messageText.isEmpty()) {
                        sendMessage(messageText);
                        editTextMessage.setText("");
                    }
                }
            });
        linearProgressIndicator.setVisibility(View.INVISIBLE);
            // 返回初始化过的视图，而不是重新调用inflater.inflate
            return view;
        }


    private void sendMessage(String messageText) {
        // Add the user's message to the list and notify adapter
        messageList.add(new Message(messageText, true));
        messageAdapter.notifyItemInserted(messageList.size() - 1);

        // Simulate a chatbot response
        linearProgressIndicator.setVisibility(View.VISIBLE);
        simulateBotResponse(messageText);
    }

    private void simulateBotResponse(String messageText) {
        ChatGptHelper.OnChatGptResponseListener chatGptResponseListener = (ChatGptHelper.OnChatGptResponseListener) getActivity();
        ChatGptHelper chatGptHelper = new ChatGptHelper(getActivity());
        chatGptHelper.setOnChatGptResponseListener(chatGptResponseListener);
        chatGptHelper.chatGPTRequest(messageText);

        String botResponse = "Robot said: " + messageText;
        linearProgressIndicator.setVisibility(View.INVISIBLE);
        // Add the bot's response to the list and notify adapter

    }


    @Override
    public void onChatGptResponse(final String response) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                linearProgressIndicator.setVisibility(View.GONE);
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    JSONArray choices = jsonResponse.getJSONArray("choices");
                    JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                    String content = message.getString("content");
                    messageList.add(new Message(content, false));
                    messageAdapter.notifyItemInserted(messageList.size() - 1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onError(String message) {

    }
    @Override
    public void onResume() {
        super.onResume();
        View rootView = getView();
        if (rootView != null) {
            ThemeUtilsActivity.applyTheme(rootView);
        }
    }
}